#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QTextEdit>
#include <QFileDialog>
#include <QDebug>
#include <fstream>
#include <QShortcut>
#include <QAction>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    //设置菜单栏
    QMenuBar *menuBar = this->menuBar();
    this->setMenuBar(menuBar);

    //设置菜单
    QMenu *menu = new QMenu("文件(&F)");
    menuBar->addMenu(menu);

    //设置菜单项
    QAction *action_save = new QAction("保存   CTRL + S");
    QAction *action_open = new QAction("打开   CTRL + O");

    menu->addAction(action_save);
    menu->addAction(action_open);

    //删除原来的中央控件
    QWidget *oldCentralWidget = this->centralWidget();
    delete oldCentralWidget;

    //设置新的中央控件
    textEdit = new QTextEdit();
    this->setCentralWidget(textEdit);

    //为两个Action绑定槽函数
    connect(action_save,&QAction::triggered,this,&MainWindow::handleSave);
    connect(action_open,&QAction::triggered,this,&MainWindow::handleOpen);

    //创建两个QShortcut
    QShortcut *shortcut1 = new QShortcut(QKeySequence(Qt::CTRL + Qt::Key_O),menu);
    QShortcut *shortcut2 = new QShortcut(QKeySequence(Qt::CTRL + Qt::Key_S),menu);

    //绑定信号槽
    connect(shortcut1,&QShortcut::activated,action_open,&QAction::trigger);
    connect(shortcut2,&QShortcut::activated,action_save,&QAction::trigger);

}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::handleSave()
{
    QString filePath = QFileDialog::getSaveFileName(this,"保存文件","D:/Codes/qt/QMenuBar_5","文本文件 (*.txt);;源文件 (*.cpp)");
    qDebug() << filePath;

    std::ofstream file(filePath.toStdString().c_str());
    if(!file.is_open()){
        qDebug() << "open file fail";
        return;
    }

    //写入数据
    //获取textEdit的文本
    const QString &context = textEdit->toPlainText();
    file << context.toStdString();

    file.close();
}

void MainWindow::handleOpen()
{
    //获取用户要打开文件的路径及文件名
    const QString &filePath = QFileDialog::getOpenFileName(this,"加载文件","D:/Codes/qt/QMenuBar_5");

    std::ifstream file(filePath.toStdString().c_str());
    if(!file.is_open()){
        qDebug() << "open file fail";
        return;
    }

    std::string content;//存储打开文本的所有正文
    std::string line;//获取每行
    while(std::getline(file,line))
    {
        content += line;
        content += '\n';
    }

    //将获取到的正文设置进textEdit中
    textEdit->setText(QString::fromStdString(content));

    file.close();
}

